package generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;

import java.util.*;

/**
 * <p>
 * mysql 代码生成器演示例子
 * </p>
 *
 * @author zjangli
 * @since 2018-09-12
 */

public class MysqlGeneratorDirectRun {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 数据源配置
     */
    private static final DataSourceConfig.Builder DATA_SOURCE_CONFIG = new DataSourceConfig
            .Builder("jdbc:mysql://localhost:3306/lims-959552?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"
            , "root"
            , "123456");

    /**
     * RUN THIS
     */
    public static void main(String[] args) {
        String moduleName = "common-server";
        FastAutoGenerator.create(DATA_SOURCE_CONFIG)
                // 全局配置
                .globalConfig(builder -> builder.author("zzh").fileOverride().enableSwagger().disableOpenDir().outputDir(System.getProperty("user.dir") + "\\" + moduleName + "\\src\\main\\java"))
                // 包配置
                .packageConfig(builder -> builder.parent("tbs.imt.data").pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir") + "\\" + moduleName + "\\src\\main\\resources\\mapper\\")))
                .injectionConfig(builder -> {
                    builder.customMap(new HashMap<String, Object>() {{
                        put("basePackage", "tbs.imt.data");
                    }}).build();
                })
                // 策略配置
                .strategyConfig((scanner, builder) -> builder
                        .addInclude(getTables(scanner.apply("请输入表名，多个英文逗号分隔？所有输入 all")))
                        .addTablePrefix("t_")
                        .controllerBuilder()
                        .enableRestStyle()
                        .entityBuilder().enableLombok().enableChainModel()
                        .enableTableFieldAnnotation()
                        .addTableFills(
                                new Column("create_time", FieldFill.INSERT),
                                new Column("create_user", FieldFill.INSERT),
                                new Column("update_time", FieldFill.INSERT_UPDATE),
                                new Column("update_user", FieldFill.INSERT_UPDATE)
                        )
                        .addIgnoreColumns("create_time","update_time", "create_user", "update_user", "valid")
                        .columnNaming(NamingStrategy.underline_to_camel)
                        .naming(NamingStrategy.underline_to_camel)
                        .entityBuilder().superClass("tbs.imt.data.entity.BaseEntity")
                        .build())
                .injectionConfig(consumer -> {
                    Map<String, String> customFile = new LinkedHashMap<>();
                    // DTO 下面的key会作为类名后缀，进而生成新类
                    customFile.put(moduleName,moduleName);
                    customFile.put("po-CreatePo.java", "templates/ftl/createPo.java.ftl");
                    customFile.put("po-CreateBatchPo.java", "templates/ftl/createBatchPo.java.ftl");
                    customFile.put("vo-DetailVo.java", "templates/ftl/detailVo.java.ftl");
                    customFile.put("po-QueryPo.java", "templates/ftl/queryPo.java.ftl");
                    customFile.put("po-UpdatePo.java", "templates/ftl/updatePo.java.ftl");
                    customFile.put("po-UpdateBatchPo.java", "templates/ftl/updateBatchPo.java.ftl");
                    customFile.put("vo-ListVo.java", "templates/ftl/listVo.java.ftl");
                    customFile.put("dto-Dto.java", "templates/ftl/dto.java.ftl");
                    consumer.customFile(customFile);
                })
                .templateEngine(new EnhanceFreemarkerTemplateEngine())
                .templateConfig(builder -> builder.controller("/templates/ftl/controller.java")
                        .entity("/templates/ftl/entity.java")
                        .mapper("/templates/ftl/mapper.java")
                        .service("/templates/ftl/service.java")
                        .serviceImpl("/templates/ftl/serviceImpl.java")
                )
                .execute();


    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }

}
